package com.wang.html2richtext.controller;

import com.wang.html2richtext.utils.CorePaser;
import com.wang.html2richtext.utils.FileUtil;
import org.apache.http.HttpResponse;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.jsoup.nodes.Document;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangzhiguo on 2019/6/16 0016.
 * 1.通过文章连接获取文章的内容
 * 2.下载文章中的图片到本地
 * 3.文章中图片连接替换为本地的图片链接
 */
@RestController
public class MainController {

   @Value("${img.filepath}")
   private String filePath;

   @Value("${img.filePathStart}")
   private String filePathStart;

   @GetMapping("html/str")
   public String showText(){
       System.out.println(filePath);
       return filePath;
   }

    @PostMapping("html/rich_text")
    @ResponseBody
    public Map html2RichText(@RequestBody String jsonStr){
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        String srcUrl = jsonStr;
        if(StringUtils.hasText(srcUrl)){
            Document document= CorePaser.getDocument(srcUrl);
            //例如文章：https://mp.weixin.qq.com/s/GoIZdwt5gJje-ZWMBUoBPw

            StringBuilder stringBuilder = new StringBuilder();
            List<Element> elementList = document.select("#img-content"); //.rich_media_content
            stringBuilder.append(elementList.toString());
            System.out.println("========================================================================");
            CorePaser corePaser = new CorePaser(filePath, filePathStart);
            if(!CollectionUtils.isEmpty(elementList)){
                elementList.forEach(e-> corePaser.downloadImg(e));
            }
//
            //替换jsoup自动src改成data-src属性
            String articleContent = stringBuilder.toString();
            Map<String, String> keyValueMap = FileUtil.keyValueMap;

            for(String url: keyValueMap.keySet()){
                articleContent = org.apache.commons.lang3.StringUtils.replace(articleContent,url, keyValueMap.get(url));
            }
            articleContent = articleContent.replace("data-src", "src");
//            System.out.println("articleContent:" + articleContent);
            result.put("data", articleContent);
        }
        return result;
    }

}
